﻿using System.Collections.Generic;
using System.Security.Principal;
using System.Web.Mvc.Html;
using System.Text;
using ProjetoComperio.Framework.Web.Security;
using System;
using System.Web.Mvc;
using System.Linq.Expressions;

namespace ProjetoComperio.Presentation.Web.GlobalResources.HtmlHelper
{

    public static class HtmlHelperExtension
    {

        #region public methods
        public static string RadioButtonList(this System.Web.Mvc.HtmlHelper htmlHelper, string fieldName, string labelValue, List<RadioButtonItem> values)
        {
            System.Text.StringBuilder html = new StringBuilder();
            foreach (var item in values)
                html.Append(item.Text + htmlHelper.RadioButton(fieldName, item.Value));

            return html.ToString();
        }

        public static string ActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string linkText, string controllerName, string actionName, IIdentity identity)
        {
            ComperioMemberShipProvider provider = new ComperioMemberShipProvider();
            return (provider.UserHasPermission(controllerName, actionName, identity.Name) ? htmlHelper.ActionLink(linkText, actionName, controllerName).ToHtmlString() : Text(linkText));

        }

        public static string CommandField(this System.Web.Mvc.HtmlHelper htmlHelper, bool enableSubmitButton, string codeForReturnButton)
        {
            StringBuilder htmlButtons = new StringBuilder();

            htmlButtons.Append("<div align='right' style='margin-top:10px'>");
            htmlButtons.Append(RenderSubmit(enableSubmitButton));
            htmlButtons.Append("&nbsp;&nbsp;");
            htmlButtons.Append(RenderReturnButton(codeForReturnButton));
            htmlButtons.Append("</div>");

            return htmlButtons.ToString();
        }
        #endregion

        #region private methods

        private static string RenderSubmit(bool enableSubmitButton)
        {
            if (enableSubmitButton)
                return "<input type='submit' id='Save' class='Button' value='Salvar' />";
            else
                return "<input type='submit' id='Save' class='Button' value='Salvar' disabled='disabled' />";

        }

        private static string RenderReturnButton(string codeForReturnButton)
        {
            return "<input type='button' id='Return' onclick=" + codeForReturnButton + " class='Button' value='Voltar' />";
        }

        private static string Text(string value)
        {

            return "<label>" + value + "</label>";
        }


        /// <summary>
        /// This method returns a validation icon 
        /// with a error message as tooltip
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static MvcHtmlString ValidationImage<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText((LambdaExpression)expression));

            if (!htmlHelper.ViewData.ModelState.ContainsKey(fullHtmlFieldName) && (htmlHelper.ViewContext == null))
                return null;

            ModelState modelState = htmlHelper.ViewData.ModelState[fullHtmlFieldName];
            ModelErrorCollection errors = (modelState == null) ? null : modelState.Errors;
            ModelError error = ((errors == null) || (errors.Count == 0)) ? null : errors[0];
            if ((error == null) && (htmlHelper.ViewContext == null))
                return null;

            var fieldValidationMetadata = new FieldValidationMetadata();

            fieldValidationMetadata.FieldName = fullHtmlFieldName;
            fieldValidationMetadata.ValidationMessageId = fullHtmlFieldName + "_validationMessage";
            fieldValidationMetadata.ReplaceValidationMessageContents = true;

            var modelClientValidationRule = new ModelClientValidationRule();

            modelClientValidationRule.ErrorMessage = " ";
            modelClientValidationRule.ValidationType = "required";
            fieldValidationMetadata.ValidationRules.Add(modelClientValidationRule);

            var item = new KeyValuePair<string, FieldValidationMetadata>(fullHtmlFieldName, fieldValidationMetadata);


            if (htmlHelper.ViewContext.FormContext != null)
                if (!htmlHelper.ViewContext.FormContext.FieldValidators.ContainsKey(item.Key))
                    htmlHelper.ViewContext.FormContext.FieldValidators.Add(item);

            TagBuilder builder = new TagBuilder("span");

            builder.Attributes["title"] = error == null ? String.Empty : error.ErrorMessage;

            builder.AddCssClass((error != null) ? "errorImage" : "field-validation-valid");
            builder.GenerateId(fullHtmlFieldName + "_validationMessage");

            return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
        }





        #endregion

    }


}
